<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Tymon\JWTAuth\Facades\JWTAuth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

//    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|string|max:255|unique:users',
            'password' => 'required|string|min:6',
            'ID' => 'required|string|max:18|unique:users,borrow_id',
            'real_name'=>'required|string',
            'phone'=>'required|string'
        ]);
    }

//获取用户的登录ip
    protected function getIp()
    {
        return \Illuminate\Support\Facades\Request::getClientIps();

    }

    protected function create(array $data)
    {
        return User::create([
            'username' => $data['username'],
            'borrow_id' => $data['ID'],
            'password' => bcrypt($data['password']),
            'login_ip' => $this->getIp()[0],
            'real_name'=>$data['real_name'],
            'phone'=>$data['phone']
        ]);
    }

    public function register(Request $request)
    {

        $validate=$this->validator($request->all());
        if($validate->fails())
        {
            $error=$validate->errors();
            return $this->fail(400006,$error);
        }

        $user = $this->create($request->all());
        $token = JWTAuth::fromUser($user);
        return $this->success(compact("token"));
    }
}
